package com.fcscs.cservice.client.main.restaurants;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.fcscs.core.common.MainPaginationSearchModel;
import com.fcscs.core.common.SearchResultsContainer;
import com.fcscs.core.common.authority.UserAuthority;
import com.fcscs.core.domain.IdNameModel;
import com.fcscs.core.domain.Property;
import com.fcscs.core.gwt.common.AsyncCallbackListener;
import com.fcscs.core.gwt.common.CoreConstants;
import com.fcscs.core.gwt.common.CoreEnums.SubmitType;
import com.fcscs.core.gwt.common.FormSubmitListener;
import com.fcscs.core.gwt.common.SearchExecutor;
import com.fcscs.core.gwt.common.SessionContext;
import com.fcscs.core.gwt.common.ui.FcsFields.ClearElementCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.EasyClearCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.FormButton;
import com.fcscs.core.gwt.common.ui.FcsFormPanel;
import com.fcscs.core.gwt.common.ui.FcsPanel;
import com.fcscs.cservice.client.common.CServiceConstants;
import com.fcscs.cservice.client.common.CserviceControllerUtils;
import com.fcscs.cservice.client.common.TextFieldAndIconButtonField;
import com.fcscs.cservice.client.common.TextFieldAndIconButtonField.TextFieldListener;
import com.fcscs.cservice.client.common.controller.BookingServiceController;
import com.fcscs.cservice.client.common.model.configuration.reservation.PropertyIdNameModelData;
import com.fcscs.cservice.client.common.model.restaurants.BookingViewModelData;
import com.fcscs.cservice.client.common.model.restaurants.RestaurantSearchItemModel;
import com.fcscs.cservice.client.common.model.restaurants.RestaurantsModelData;
import com.fcscs.cservice.common.CServiceCommonEnums.BookingStatus;
import com.fcscs.cservice.domain.Restaurant;
import com.fcscs.cservice.domain.model.BookingView;
import com.fcscs.share.gwt.common.ShareGWTConstants;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;

public class RestaurantsPanel extends FcsPanel {
	private VerticalPanel vp;

	private EasyClearCombobox<PropertyIdNameModelData> prosComBox;
	private LayoutContainer container;
	private ListStore<PropertyIdNameModelData> propStore;
	private Label prosLab;
	private Label restaurantLab;
	private ClearElementCombobox<RestaurantsModelData> restaurantCombox;
	private ListStore<RestaurantsModelData> restaurantStore;
	private HorizontalPanel propHp;
	private HorizontalPanel restaurantHp;
	private FormButton advancedSearchButton;
	private RestaurantsDetailDialog restaurantsDetailDialog;
	private GuestDetailGrid myGrid;
	private Long restaurantId;
	private long propId;
	private List<BookingViewModelData> bookingViewList;
	private LayoutContainer container1;
	private TextFieldAndIconButtonField searchFieldBtn ;
	private FormPanel myFormPanel;
	private HorizontalPanel hp1;
	private HorizontalPanel hp2;
	private boolean isAdvancedSearch;
	private RestaurantSearchItemModel searchItemModel;

	public RestaurantsPanel(String id) {
		super(id);
	}

	@Override
	public void init() {
		vp = new VerticalPanel();
		vp.setSpacing(5);
		
		myFormPanel = new FormPanel();
		myFormPanel.setHeading(CoreConstants.CORE_MESSAGES.operation(
				CServiceConstants.CSERVICE_CONSTANTS.restaurant(), CoreConstants.CORE_CONSTANTS.search()));
		myFormPanel.setSize(960, 100);
		myFormPanel.setFrame(true);
		myFormPanel.setId("RestaurantsPanel_myFormPanel");
		vp.add(myFormPanel);
		
		hp1 = new HorizontalPanel();
		hp1.setSpacing(5);
		hp1.setId("RestaurantsPanel_hp1");
		myFormPanel.add(hp1);
		
		container = new LayoutContainer();
		container.setLayout(new ColumnLayout());
		hp1.add(container);
		
		propHp = new HorizontalPanel();
		propHp.setId("RestaurantsPanel_propHp");

		prosLab = new Label(CoreConstants.CORE_MESSAGES.operation(
				CoreConstants.CORE_CONSTANTS.property(), CoreConstants.REQURIED_FIELD_LABEL));
		prosLab.setId("RestaurantsPanel_prosLab");

		prosComBox = new EasyClearCombobox<PropertyIdNameModelData>();
		prosComBox.focus();
		prosComBox.setDisplayField(CoreConstants.FULLTNAME);
		propStore = new ListStore<PropertyIdNameModelData>();
		prosComBox.setWidth(200);
		prosComBox.setStore(propStore);
		prosComBox.setId("RestaurantsPanel_prosComBox");
		prosComBox.setFieldLabel(CoreConstants.CORE_CONSTANTS.property());
		prosComBox.setEmptyText(CServiceConstants.CSERVICE_CONSTANTS.choosePro());
		prosComBox.setTriggerAction(TriggerAction.ALL);
		prosComBox.setForceSelection(true);
		prosComBox.setFireChangeEventOnSetValue(true);
		prosComBox.addSelectionChangedListener(new SelectionChangedListener<PropertyIdNameModelData>() {
			
			@Override
			public void selectionChanged(SelectionChangedEvent<PropertyIdNameModelData> se) {
				if (null != prosComBox.getValue()) {
					Long propId = prosComBox.getValue().getEntity().getId();
					CserviceControllerUtils.getInstance().getRestaurantList(propId, restaurantStore);
					newSearch(true);
				}
			}
		});
		propHp.add(prosComBox);
		
		container.add(prosLab, new ColumnData(80));
		container.add(propHp, new ColumnData(250));
		
		
		restaurantHp = new HorizontalPanel();
		restaurantHp.setId("RestaurantsPanel_restaurantHp");
		
		restaurantLab = new Label(CServiceConstants.CSERVICE_CONSTANTS.restaurant());
		restaurantLab.setId("RestaurantsPanel_prosLab");

		restaurantCombox = new ClearElementCombobox<RestaurantsModelData>(new RestaurantsModelData(new Restaurant()));
		restaurantCombox.setDisplayField(CoreConstants.FULLTNAME);
		restaurantStore = new ListStore<RestaurantsModelData>();
		restaurantCombox.setWidth(200);
		restaurantCombox.setStore(restaurantStore);
		restaurantCombox.setId("RestaurantsPanel_prosComBox");
		restaurantCombox.setFieldLabel(CoreConstants.CORE_CONSTANTS.property());
		restaurantCombox.setEmptyText(CServiceConstants.CSERVICE_CONSTANTS.chooseRestaurant());
		restaurantCombox.setTriggerAction(TriggerAction.ALL);
		restaurantCombox.setForceSelection(true);
		restaurantCombox.setFireChangeEventOnSetValue(true);
		restaurantHp.add(restaurantCombox);
		restaurantCombox.addSelectionChangedListener(new SelectionChangedListener<RestaurantsModelData>() {

			@Override
			public void selectionChanged(SelectionChangedEvent<RestaurantsModelData> se) {
				newSearch(true);
			}
		});
		container.add(restaurantLab, new ColumnData(80));
		container.add(restaurantHp, new ColumnData(220));
		
		
		hp2 = new HorizontalPanel();
		hp2.setSpacing(5);
		hp2.setId("RestaurantsPanel_hp1");
		myFormPanel.add(hp2);
		
	    container1 = new LayoutContainer();
		container1.setLayout(new ColumnLayout());
		hp2.add(container1);
		
		Label l = new Label(CoreConstants.CORE_CONSTANTS.search()+ CServiceConstants.FIELD_SEP);
		container1.add(l,new ColumnData(80));

		searchFieldBtn = new TextFieldAndIconButtonField(new TextFieldListener() {

			@Override
			public void onTextFieldEnterKeyPressSearch(String value) {
				if (value == null || value.trim().isEmpty()) {
					newSearch(true);
				} else {
					newSearch(false);
				}
			}

			@Override
			public void onIconButtoSearch(String value) {
				if (value == null || value.trim().isEmpty()) {
					newSearch(true);
				} else {
					newSearch(false);
				}
			}
		});
		container1.add(searchFieldBtn,new ColumnData(250));
		
		advancedSearchButton = new FormButton(CServiceConstants.CSERVICE_CONSTANTS.advancedSearch());
	    advancedSearchButton.setId("ReservationPanel_advancedSearchButton");
	    advancedSearchButton.addSelectionListener(new SelectionListener<ButtonEvent>(){
			@Override
			public void componentSelected(ButtonEvent ce) {
				restaurantsDetailDialog = RestaurantsDetailDialog.getInstance(new FormSubmitListener<BookingView>() {
					
					@Override
					public void formSubmitCallBack(FcsFormPanel<BookingView> form, SubmitType submitType) {
						newSearch(true);
						restaurantsDetailDialog.hide();
					}
				});
				restaurantsDetailDialog.show();
				isAdvancedSearch = true;
			}
	    });
	    container1.add(advancedSearchButton);
	    
		myGrid = new GuestDetailGrid(CServiceConstants.CSERVICE_CONSTANTS.bookingView(),
				new SearchExecutor<BookingViewModelData, MainPaginationSearchModel>() {

					@Override
					public void doSearch(final MainPaginationSearchModel searchModel,
							final AsyncCallback<BasePagingLoadResult<BookingViewModelData>> callback) {
						propId = prosComBox.getValue().getEntity().getId();
						if (null != restaurantCombox.getValue()) {
							restaurantId = restaurantCombox.getValue().getEntity().getId();
						} else {
							restaurantId = null;
						}
						if (!isAdvancedSearch) {
							BookingServiceController.getInstance().simpleFindBookings(propId, restaurantId,
									null, new Date(), 0, 20,
									new AsyncCallbackListener<SearchResultsContainer<BookingView>>() {

										@Override
										public void onLogin(String username) {
											BookingServiceController.getInstance().simpleFindBookings(propId,
													restaurantId, null, new Date(), 0, 20, this);
										}

										@Override
										public void onSuccess(SearchResultsContainer<BookingView> result) {
											if (null != result) {
												// isFirstLoad = false;
												bookingViewList = new ArrayList<BookingViewModelData>();
												for (BookingView bv : result.getResults()) {
													bookingViewList.add(new BookingViewModelData(bv));
												}
												callback.onSuccess(FcsPanel.createPagingLoadResult(
														bookingViewList, searchModel.getCurrentPage(),
														searchModel.getResultsPerPage(), result.getTotalCnt()));
											}
										}

										@Override
										public void onFailure(Throwable caught) {
											MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(
													CoreConstants.CORE_CONSTANTS.system(),
													ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
													CoreConstants.CORE_CONSTANTS.systemError(), null);
										}
									});
						} else {
							searchItemModel = new RestaurantSearchItemModel();
							createSearchTerm(restaurantsDetailDialog.searchItemCombo1.getValue().getEnum().getIndex(), 1);
							createSearchTerm(restaurantsDetailDialog.searchItemCombo2.getValue().getEnum().getIndex(), 2);
							createSearchTerm(restaurantsDetailDialog.searchItemCombo3.getValue().getEnum().getIndex(), 3);
							BookingServiceController.getInstance().advancedFindBookings(propId,
									restaurantId, null, searchItemModel.getFirstName(),
									searchItemModel.getLastName(), null, searchItemModel.getGuestType(),
									null, searchItemModel.getBookingStatus(),
									searchItemModel.getFromDate(), searchItemModel.getToDate(), 0, 20,
									new AsyncCallbackListener<SearchResultsContainer<BookingView>>() {

										@Override
										public void onLogin(String username) {
											BookingServiceController.getInstance().advancedFindBookings(propId,
													restaurantId, null, searchItemModel.getFirstName(),
													searchItemModel.getLastName(), null, searchItemModel.getGuestType(),
													null, searchItemModel.getBookingStatus(),
													searchItemModel.getFromDate(), searchItemModel.getToDate(), 0, 20,this);
										}

										@Override
										public void onFailure(Throwable caught) {
											MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(
													CoreConstants.CORE_CONSTANTS.system(),
													ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
													CoreConstants.CORE_CONSTANTS.systemError(), null);
										}

										@Override
										public void onSuccess(SearchResultsContainer<BookingView> result) {
											if (null != result) {
												bookingViewList = new ArrayList<BookingViewModelData>();
												for (BookingView bv : result.getResults()) {
													bookingViewList.add(new BookingViewModelData(bv));
												}
												isAdvancedSearch = false;
												callback.onSuccess(FcsPanel.createPagingLoadResult(
														bookingViewList, searchModel.getCurrentPage(),
														searchModel.getResultsPerPage(),
														result.getTotalCnt()));
											}
										}
									});
						}
					}
				});

		vp.add(myGrid);
		
//		restaurantsGrid = new RestaurantsGrid(CServiceConstants.CSERVICE_CONSTANTS.restaurant(), null);
//		restaurantsGrid.setHeaderVisible(true);
//		restaurantsGrid.setId("RestaurantsPanel_restaurantsGrid");
//		vp.add(restaurantsGrid);
		add(vp);
		onShow();
	}
	
	
	private void createSearchTerm(int code, int row) {
		switch (code) {
		case 0:
			switch (row) {
			case 1:
				if (restaurantsDetailDialog.firstName1.getValue() != null) {
					searchItemModel.setFirstName(restaurantsDetailDialog.firstName1.getValue().trim());
				} else {
					searchItemModel.setFirstName(null);
				}
				if (restaurantsDetailDialog.lastName1.getValue() != null) {
					searchItemModel.setLastName(restaurantsDetailDialog.lastName1.getValue().trim());
				} else {
					searchItemModel.setLastName(null);
				}
				break;
			case 2:
				if (restaurantsDetailDialog.firstName2.getValue() != null) {
					searchItemModel.setFirstName(restaurantsDetailDialog.firstName2.getValue().trim());
				} else {
					searchItemModel.setFirstName(null);
				}
				if (restaurantsDetailDialog.lastName2.getValue() != null) {
					searchItemModel.setLastName(restaurantsDetailDialog.lastName2.getValue().trim());
				} else {
					searchItemModel.setLastName(null);
				}
				break;
			case 3:
				if (restaurantsDetailDialog.firstName3.getValue() != null) {
					searchItemModel.setFirstName(restaurantsDetailDialog.firstName3.getValue().trim());
				} else {
					searchItemModel.setFirstName(null);
				}
				if (restaurantsDetailDialog.lastName3.getValue() != null) {
					searchItemModel.setLastName(restaurantsDetailDialog.lastName3.getValue().trim());
				} else {
					searchItemModel.setLastName(null);
				}
				break;
			}
			break;
		case 1:
			switch (row) {
			case 1:
				if (restaurantsDetailDialog.bookingStatusCombo1.getValue() != null) {
					List<BookingStatus> statusList = new ArrayList<BookingStatus>();
					statusList.add(restaurantsDetailDialog.bookingStatusCombo1.getValue().getEnum().getBookingStatus());
					searchItemModel.setBookingStatus(statusList);
				} else {
					searchItemModel.setBookingStatus(null);
				}
				break;
			case 2:
				if (restaurantsDetailDialog.bookingStatusCombo2.getValue() != null) {
					List<BookingStatus> statusList = new ArrayList<BookingStatus>();
					statusList.add(restaurantsDetailDialog.bookingStatusCombo2.getValue().getEnum().getBookingStatus());
					searchItemModel.setBookingStatus(statusList);
				} else {
					searchItemModel.setBookingStatus(null);
				}
				break;
			case 3:
				if (restaurantsDetailDialog.bookingStatusCombo3.getValue() != null) {
					List<BookingStatus> statusList = new ArrayList<BookingStatus>();
					statusList.add(restaurantsDetailDialog.bookingStatusCombo3.getValue().getEnum().getBookingStatus());
					searchItemModel.setBookingStatus(statusList);
				} else {
					searchItemModel.setBookingStatus(null);
				}
				break;
			}
			break;
		case 2:
			switch (row) {
			case 1:
				if (restaurantsDetailDialog.fromDateField1.getValue() != null && restaurantsDetailDialog.toDateField1.getValue() != null) {
					searchItemModel.setFromDate(restaurantsDetailDialog.fromDateField1.getValue());
					searchItemModel.setToDate(restaurantsDetailDialog.toDateField1.getValue());
				} else {
					searchItemModel.setFromDate(null);
					searchItemModel.setToDate(null);
				}
				break;
			case 2:
				if (restaurantsDetailDialog.fromDateField2.getValue() != null && restaurantsDetailDialog.toDateField2.getValue() != null) {
					searchItemModel.setFromDate(restaurantsDetailDialog.fromDateField2.getValue());
					searchItemModel.setToDate(restaurantsDetailDialog.toDateField2.getValue());
				} else {
					searchItemModel.setFromDate(null);
					searchItemModel.setToDate(null);
				}
				break;
			case 3:
				if (restaurantsDetailDialog.fromDateField3.getValue() != null && restaurantsDetailDialog.toDateField3.getValue() != null) {
					searchItemModel.setFromDate(restaurantsDetailDialog.fromDateField3.getValue());
					searchItemModel.setToDate(restaurantsDetailDialog.toDateField3.getValue());
				} else {
					searchItemModel.setFromDate(null);
					searchItemModel.setToDate(null);
				}
				break;
			}
			break;
		// case 3:
		// switch(row){
		// case 1:
		// searchItemModel.setArrivStart(dateField11.getValue());
		// searchItemModel.setArrivEnd(dateField12.getValue());
		// break;
		// case 2:
		// searchItemModel.setArrivStart(dateField21.getValue());
		// searchItemModel.setArrivEnd(dateField22.getValue());
		// break;
		// case 3:
		// searchItemModel.setArrivStart(dateField31.getValue());
		// searchItemModel.setArrivEnd(dateField32.getValue());
		// break;
		// }
		// break;
		// case 4:
		// switch(row){
		// case 1:
		// searchItemModel.setDepartStart(dateField11.getValue());
		// searchItemModel.setDepartEnd(dateField12.getValue());
		// break;
		// case 2:
		// searchItemModel.setDepartStart(dateField21.getValue());
		// searchItemModel.setDepartEnd(dateField22.getValue());
		// break;
		// case 3:
		// searchItemModel.setDepartStart(dateField31.getValue());
		// searchItemModel.setDepartEnd(dateField32.getValue());
		// break;
		// }
		// break;
		}
	}



	@Override
	public UserAuthority getRequiredAuthority() {
		return null;
	}

	@Override
	protected Widget getViewPanel() {
		return null;
	}

	@Override
	public boolean onHide() {
		return true;
	}

	public void loadPropStore() {
		propStore.removeAll();
		List<IdNameModel<Property>> listIdNameModel = SessionContext.getInstance().getPropertyGroup();
		IdNameModel<Property> noGroup = new IdNameModel<Property>(SessionContext.getInstance()
				.getPropertyId(), SessionContext.getInstance().getPropertyName());
		if (listIdNameModel.size() == 0) {
			propStore.add(new PropertyIdNameModelData(noGroup));
		} else {
			for (IdNameModel<Property> inm : listIdNameModel) {
				propStore.add(new PropertyIdNameModelData(inm));
			}
		}
		prosComBox.setValue(propStore.findModel(CoreConstants.ID, SessionContext.getInstance()
				.getPropertyId()));
	}
	
	protected void newSearch(boolean all) {
		String term = null;
		if (all) {
			term = null;
		}else {
			term = searchFieldBtn.getTextFieldValue().trim();
		}
		MainPaginationSearchModel sm = new MainPaginationSearchModel();
		sm.setSearchTerm(term);
		myGrid.newSearch(sm);
	}
	
	@Override
	public void onShow() {
		loadPropStore();
	}
}
